import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { CarService } from '../car.service';
import * as ons from 'onsenui';
import * as Hammer from 'hammerjs';

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {
  @ViewChild('carousel') carousel;

  get banner() { return this.carService.banner.data }
  get car() { return this.carService.car.data }
  get carLoading() { return !this.carService.car.requestSent }
  autoBannerTimer;

  constructor(private route: Router, private carService: CarService ) {
    this.carService.getBanner()
    this.carService.getCarList()
    this.autoBannerTimer = setInterval(()=>{
      const carousel = this.carousel.nativeElement;
      if(carousel.getActiveIndex() === this.banner.length-1) carousel.prev();
      else carousel.next();
    },5000)
   }

  add(): void {
    this.route.navigate(['addCar'])
  }

  async deleteCar(car) {
    const {success, msg} = await this.carService.deleteCar(car.car_id);
    if(success) {
      ons.notification.toast('已删除本车!', {timeout: 2000});
    } else {
      ons.notification.toast(msg, {timeout: 2000});
    }
  }

  swipeLeft(e){
    const dom:HTMLElement = e.target.parentElement.parentElement;
      if(dom.classList[0]==='list-item'){
        dom.parentElement.classList.add('swipe-left');
     }
  }

  swipeRight(e){
    const dom:HTMLElement = e.target.parentElement.parentElement;
      if(dom.classList[0]==='list-item'){
        dom.parentElement.classList.remove('swipe-left');
      }
  }

  ngOnInit() {
      const $carList = document.getElementById('car_list');
      const hammer = new Hammer($carList)
      hammer.on('panleft', this.swipeLeft)
      hammer.on('panright', this.swipeRight)
  }

  ngOnDestroy() {
    clearInterval(this.autoBannerTimer);
  }

}
